<?php
/**
 * Created by PhpStorm.
 * User: Yui
 * Date: 2017/5/16 0016
 * Time: 14:31
 */

namespace common\models;

use common\services\AliSmsSve;
use common\services\SmsLogSve;
use yii\base\Model;

class MemberSmsLogin extends Model
{
    public $mobile;
    public $verify_code;
    private $_Member;

    public function rules()
    {

        return [
            [['mobile', 'verify_code'], 'required'],
            ['mobile', 'match', 'pattern' => '/^1[34578]\d{9}$/', 'message' => '手机号码格式错误'],

            ['verify_code', 'string', 'min' => OC['sms_code_len'], 'message' => '验证码至少' . OC['sms_code_len'] . '个字符'],
            ['verify_code', 'validateCode', 'message' => '手机号或验证码错误'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'mobile' => '手机号码',
            'verify_code' => '验证码',
        ];
    }

    /**
     * 验证短信
     * @param $attribute
     * @param $params
     */
    public function validateCode($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $Member = $this->getMember();
            if (empty($Member)) {
                $this->addError($attribute, '手机号码或验证码错误');
            }
            //检查验证码
            $AliSmsSve = new AliSmsSve();
            $rs = $AliSmsSve->checkVerifyCode($this->mobile, 'login', $this->verify_code);
            if ($rs['code'] !== 0) {
                $this->addError($attribute, $rs['msg']);
                return;
            }
        }

    }


    public function getMember()
    {
        if ($this->_Member === null) {
            $this->_Member = Member::findByMobile($this->mobile);
        }
        return $this->_Member;
    }
}